package com.sen.app.timemail.utils;

import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.apache.log4j.Logger;

import com.sen.app.timemail.utils.cfg.AppPropReader;

/**
 * 发送电子邮件工具类
 * 
 * @author sen
 */
public class SendEmailUtils {

	/** 日志记录器 */
	private static Logger log = Logger.getLogger(SendEmailUtils.class);
	
	/** HTML 邮件内容 contentType */
	public static String HTML_EMAIL_CONTENTTYPE = "text/html;charset=utf-8";
	
	/** 纯文本邮件内容contentType */
	public static String TXT_EMAIL_CONTENTTYPE = "text/plain;charset=utf-8";

	/**
	 * 发送电子邮件
	 * @param to 接收者邮箱地址
	 * @param emailSubject 邮件主题
	 * @param emailContent 邮件内容
	 * @param contentType 邮件内容类型
	 * @return String 发送结果
	 */
	public static String send(String to, String emailSubject, String emailContent, String contentType) {

		HtmlEmail htmlEmail = new HtmlEmail();
		String retVal = "";

		try {
			// 设置接收邮件的邮件服务器
			htmlEmail.setHostName(AppPropReader.getPropertie("send.email.hostName"));
			// 用户名密码验证
			htmlEmail.setAuthenticator(new DefaultAuthenticator(AppPropReader.getPropertie("send.email.userName"),
					AppPropReader.getPropertie("send.email.password")));
			htmlEmail.addTo(to);
			htmlEmail.setFrom(AppPropReader.getPropertie("send.email.adrress"));
			htmlEmail.setSubject(emailSubject);
			htmlEmail.setMsg(emailContent);
			htmlEmail.setContent(emailContent, contentType);
			retVal = htmlEmail.send();
		} catch (EmailException e) {
			log.error(e.getMessage(), e);
			throw new RuntimeException("邮件服务器连接失败，请稍后再试...", e);
		} catch (RuntimeException e) {
			log.error(e.getMessage(), e);
			throw new RuntimeException("系统异常，请稍后再试...", e);
		}
		return retVal;
	}

	/**
	 * 发送HTML格式电子邮件
	 * @param to 接收者邮箱地址
	 * @param emailSubject 邮件主题
	 * @param emailContent 邮件内容
	 */
	public static String sendHtml(String to, String emailSubject, String emailContent) {
		return send(to, emailSubject, emailContent, SendEmailUtils.HTML_EMAIL_CONTENTTYPE);
	}

	/**
	 * 发送文本格式电子邮件
	 * @param to 接收者邮箱地址
	 * @param emailSubject 邮件主题
	 * @param emailContent 邮件内容
	 */
	public static String sendText(String to, String emailSubject, String emailContent) {
		return send(to, emailSubject, emailContent, SendEmailUtils.TXT_EMAIL_CONTENTTYPE);
	}
	
	public static String send(Email email) {
		
		
		
		return "";
	}
}
